package xyz.lovegu.server.sys.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import xyz.lovegu.server.sys.common.Constant;
import xyz.lovegu.server.sys.common.DataGridView;
import xyz.lovegu.server.sys.common.ResultObj;
import xyz.lovegu.server.sys.dos.User;
import xyz.lovegu.server.sys.mapper.UserMapper;
import xyz.lovegu.server.sys.service.UserService;
import xyz.lovegu.server.sys.vos.UserVo;
import java.util.List;

/**
 * @author 老顾
 * @title: UserserviceImpl
 * @projectName campus-prevention-system
 * @email: 1437594522@qq.com
 * @date 2022/5/4 23:43
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResultObj addStudent(UserVo userVo) {
        try {
            //设置类型
            userVo.setType(Constant.USER_TYPE_STUDENT);
            //设置盐
            String saltS = IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(saltS);
            //设置默认密码
            userVo.setPassword(new Md5Hash(Constant.USER_DEFAULT_PWD,saltS,2).toString());
            //设置用户默认头像
            userVo.setImgpath(Constant.DEFAULT_IMG_USER);
            this.save(userVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 添加老师
     *
     * @param userVo
     * @return
     */
    @Override
    public ResultObj addTeacher(UserVo userVo) {
        try {
            //设置类型
            userVo.setType(Constant.USER_TYPE_TEACHER);
            //设置盐
            String saltT = IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(saltT);
            //设置默认密码
            userVo.setPassword(new Md5Hash(Constant.USER_DEFAULT_PWD,saltT,2).toString());
            //设置用户默认头像
            userVo.setImgpath(Constant.DEFAULT_IMG_USER);
            this.save(userVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 根据id删除用户
     *
     * @param userVo
     * @return
     */
    @Override
    public ResultObj delUserById(UserVo userVo) {
        //查询用户是否存在
        User user = this.getById(userVo.getId());
        if (user==null) {
            return ResultObj.USER_NOT_EXIST;
        }
        try {
            this.removeById(userVo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 根据id查询一个用户
     *
     * @param id
     * @return
     */
    @Override
    public Object getUserById(Integer id) {
        User user = this.getById(id);
        if (user==null) {
            return ResultObj.USER_NOT_EXIST;
        }else {
            return new DataGridView(user);
        }
    }

    /**
     * 修改用户
     *
     * @param userVo
     * @return
     */
    @Override
    public ResultObj updateUserInfo(UserVo userVo) {
        //查询用户是否存在
        User user = this.getById(userVo.getId());
        if (user==null) {
            return ResultObj.USER_NOT_EXIST;
        }
        try {
            //修改要set,get
            user.setName(userVo.getName());
            user.setAddress(userVo.getClasses());
            user.setGender(userVo.getGender());
            user.setClassId(userVo.getClassId());
            user.setClasses(userVo.getClasses());
            this.updateById(user);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 重置用户密码
     *
     * @param userVo
     * @return
     */
    @Override
    public ResultObj resetUserPassword(UserVo userVo) {
        try {
            User user = new User();
            user.setId(userVo.getId());
            //设置盐  32位(大写英文字母(A-Z)加数字(0-9))
            String salt = IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);
            //设置密码
            user.setPassword(new Md5Hash(Constant.USER_DEFAULT_PWD,salt,2).toString());
            this.updateById(user);
            return ResultObj.RESET_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }

    /**
     * 修改用户密码
     *
     * @param userVo
     * @return
     */
    @Override
    public ResultObj updateUserPassword(UserVo userVo) {
        //将oldPassword加盐并散列两次在和数据库中的密码进行对比
        User user1 = this.getById(userVo.getId());
        //获得该用户的盐
        String salt = user1.getSalt();
        //通过用户输入的原密码，从数据库中查出的盐，散列次数生成新的旧密码
        String oldPassword2 = new Md5Hash(userVo.getOldPassword(),salt, Constant.HASHITERATIONS).toString();
        if (oldPassword2.equals(user1.getPassword())){
            if (userVo.getNewPasswordOne().equals(userVo.getNewPasswordTwo())){
                //生成新的密码
                String newPassword = new Md5Hash(userVo.getNewPasswordOne(),salt, Constant.HASHITERATIONS).toString();
                user1.setPassword(newPassword);
                this.updateById(user1);
                return ResultObj.UPDATE_SUCCESS;
            }else {
                return ResultObj.UPDATE_ERROR;
            }
        }else {
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 根据班级id查询学生
     *
     * @param classId
     * @return
     */
    @Override
    public Object getClassIdByStudent(Integer classId) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(classId!=null,User::getClassId,classId);
        lambdaQueryWrapper.eq(User::getAvailable,Constant.AVAILABLE_TRUE);
        lambdaQueryWrapper.eq(User::getType,Constant.USER_TYPE_STUDENT);
        List<User> list = this.list(lambdaQueryWrapper);
        for (User user : list) {
            System.out.println(user.toString());
        }
        return new DataGridView(list);
    }

    /**
     * 根据班级id查询老师
     *
     * @param classId
     * @return
     */
    @Override
    public Object getClassIdByTeacher(Integer classId) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(classId!=null,User::getClassId,classId);
        lambdaQueryWrapper.eq(User::getAvailable,Constant.AVAILABLE_TRUE);
        lambdaQueryWrapper.eq(User::getType,Constant.USER_TYPE_TEACHER);
        List<User> list = this.list(lambdaQueryWrapper);
        for (User user : list) {
            System.out.println(user.toString());
        }
        return new DataGridView(list);
    }

    /**
     * 查询所有用户
     *
     * @param userVo
     * @return
     */
    @Override
    public DataGridView getAllUsers(UserVo userVo) {
        IPage<User> page = new Page<User>(userVo.getPage(),userVo.getLimit());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据用户登录名称以及用户名称模糊查询用户
        lambdaQueryWrapper.like(StringUtils.isNotBlank(userVo.getName()),User::getLoginName,userVo.getName()).or().eq(StringUtils.isNotBlank(userVo.getName()),User::getName,userVo.getName());
        lambdaQueryWrapper.like(StringUtils.isNotBlank(userVo.getAddress()),User::getAddress,userVo.getAddress());
        //查询学生和老师
        lambdaQueryWrapper.eq(User::getType,Constant.USER_TYPE_STUDENT).or().eq(User::getType,Constant.USER_TYPE_TEACHER);
        lambdaQueryWrapper.eq(userVo.getClassId()!=null,User::getClassId,userVo.getClassId());
        lambdaQueryWrapper.orderByDesc(User::getId);
        this.page(page,lambdaQueryWrapper);
        //将所有用户数据放入list中
        List<User> list = page.getRecords();
        return new DataGridView(page.getTotal(),list);
    }
}
